package com.yh.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.yh.dao.UserDao;
import com.yh.dao.impl.UserDaoImpl;
import com.yh.model.UserModel;

public class UserController extends ActionSupport implements ModelDriven<UserModel>{
	private static final long serialVersionUID = 1L;
	private UserModel user;
	
	public UserModel getUser() {
		return user;
	}
	public void setUser(UserModel user) {
		this.user = user;
	}

	/**
	 * 获取用户列表
	 * @return
	 */
	public String getAll(){
		UserDao userResult = new UserDaoImpl();
		List<UserModel> userList =  userResult.getAll();
		System.out.println(userList.get(0).getPassword());
		ServletActionContext.getRequest().setAttribute("userList",userList);
		//System.out.println(userList.get(0).getUsername()+"/t"+userList.get(1).getUsername());
		return SUCCESS;
	}
	/**
	 * 删除用户
	 * @return
	 * @throws IOException 
	 */
	public String deleteUser() throws IOException{
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = response.getWriter();
		UserDao userResult = new UserDaoImpl();
		userResult.deleteUser(getModel().getId());
		out.print("{\"rscode\":\"1\",\"rsMsg\":\"删除成功\"}");
		out.flush();
		out.close();
		
		return SUCCESS;
	}
	/**
	 * 新增用户
	 * @return
	 */
	public String addUser(){
		UserDao userResult = new UserDaoImpl();		
		userResult.addUser(user);
		return SUCCESS;
	}
	/**
	 * 修改用户
	 * @return
	 * */
	public String findUserById(){
		UserDao userResult=new UserDaoImpl();
		user=userResult.findUserById(getModel().getId());
		ServletActionContext.getRequest().setAttribute("user", user);
		return SUCCESS;
		
	}
	public String updateUser(){
		UserDao userResult = new UserDaoImpl();
		System.out.println("控制层用户名："+getModel().getName());
		System.out.println("控制层用户密码："+getModel().getPassword());
		
		userResult.updateUser(user);
		return SUCCESS;
	}
	/**
	 * 查询用户
	 * @return
	 */
	public String selectUser(){
		UserDao userResult = new UserDaoImpl();
		user=userResult.selectUser(getModel().getName());
		//user = userResult.findUserByName(getModel().getname());
		ServletActionContext.getRequest().setAttribute("user",user);
		return SUCCESS;
	}
	
	public UserModel getModel() {
		if(user==null){
			user = new UserModel();
		}
		return user;
	}
	
}
